<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  getThingModelDetail,
  saveThingModel,
  updateThingModel,
} from '#/api/iot/product/thingModel';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits(['success', 'reload']);
const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 100,
    formItemClass: 'col-span-2',
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      label: 'id',
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
    },
    {
      label: 'productId',
      fieldName: 'productId',
      component: 'Input',
      dependencies: {
        show: () => false,
        triggerFields: [''],
      },
    },
    {
      fieldName: 'blockName',
      label: '模块名称',
      component: 'Input',
      rules: 'required',
      componentProps: {
        maxlength: 30,
        showCount: true,
      },
    },
    {
      fieldName: 'blockIdentifier',
      label: '模块标识符',
      rules: 'required',
      component: 'Input',
      componentProps: {
        maxlength: 30,
        showCount: true,
      },
      dependencies: {
        disabled(values) {
          return !!values.id;
        },
        triggerFields: ['id'],
      },
      help: '支持英文大小写字母、数字和下划线，不超过 30个字符。',
    },
  ],
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id, productId } = drawerApi.getData() as {
      id?: number | string;
      productId: string;
    };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await getThingModelDetail(id);
      await formApi.setValues(record);
    }
    if (productId) {
      await formApi.setValues({ productId });
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? updateThingModel(data) : saveThingModel(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[400px]">
    <BasicForm />
  </BasicModal>
</template>
